<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Db;
use think\Request;
use think\Validate;

header("Content-type: text/html; charset=utf-8");

class Notify extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 是否读取消息
     * @return mixed
     */
    public function is_read(){
        $data = input();

        $isread = Db::name('notify')->field('isread')->where('id',$data['id'])->find();
        if($isread['isread']==0){
            $insert = [
                'read_time'=>time(),
                'isread' => 1,
            ];
            $info = Db::name('notify')->where('id',$data['id'])->update($insert);
//            $info = Db::name('notify')->where('id',$data['id'])->setField('isread', 1);
        }else{
            $info = Db::name('notify')->where('id',$data['id'])->setField('isread', 0);
        }
        $notify = Db::name('notify')->select();
        $this->view->assign('list',$notify);
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $data = input();
        if ($data['isread'] == 1){
            $map['n.isread'] = ['eq',1];
        }elseif($data['isread'] == 2){
            $map['n.isread'] = ['eq',0];
        }
        if ($data['user_name']){
            $userId = Db::name('admin_user')->where('realname','like','%'.$data['user_name'].'%')->field('id')->select();
            if ($userId){
                $userIds = '';
                foreach ($userId as $uk=>$uv){
                    $userIds .= $uv['id'].',';
                }
                $map['u.id'] = ['in',rtrim($userIds,',')];
            }
        }
        if ($data['title']){
            $map['n.title'] = ['like','%'.$data['title'].'%'];
        }
        if ($data['create_time']){
            $start_create_time = strtotime($data['create_time'].' 0:0:0');
            $end_create_time = strtotime($data['create_time'].' 23:59:59');
            $map['n.create_time'] = ['between',[$start_create_time,$end_create_time]];
        }
        if ($data['read_time']){
            $start_read_time = strtotime($data['read_time'].' 0:0:0');
            $end_read_time = strtotime($data['read_time'].' 23:59:59');
            $map['n.read_time'] = ['between',[$start_read_time,$end_read_time]];
        }
        if ($data['type'] && $data['type'] != 3){
            $map['n.type'] = $data['type'];
        }
        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
        $map['n.isdelete'] = ['eq',0];
        $list = Db::name('Notify')
            ->alias('n')
            ->join("tp_admin_user u" ,"u.id=n.user_id","left")
            ->field("n.*,u.realname")
            ->where($map)
            ->order('n.id','desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $type = [
            ['name'=>'司导审核结果','value'=>'driver_check_result'],
            ['name'=>'系统普通消息','value'=>'system_ordinary_info'],
            ['name'=>'新的订单','value'=>'news_order'],
            ['name'=>'已结算','value'=>'checkouted'],
            ['name'=>'考试通过','value'=>'exam_pass'],
            ['name'=>'升级','value'=>'upgrade'],
            ['name'=>'司机升级申请','value'=>'driver_rank_apply'],
            ['name'=>'司机降级申请','value'=>'driver_degrade_appeal'],
            ['name'=>'旅客分组信息','value'=>'dispatch_traveler_group'],
        ];

        // 模板赋值显示
        $this->view->assign('list', $list);
        $this->view->assign('type', $type);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * @title 添加信息
     * @author 邓汉炜
     * @url /admin/notify/add
     * @param Request $request
     * @return \think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            $rule = [
                'user_id'=>'require',
                'type'=>'require',
                'content'=>'require',
                'title'=>'require',
            ];
            $msg = [
                'user_id.require'=>'缺少用户',
                'type.require'=>'缺少消息类型',
                'content.require'=>'缺少内容',
                'title.require'=>'缺少标题',
            ];
            $validate = new Validate($rule,$msg);
            $result = $validate->check($postData);
            if (!$result){
                return ajax_return_adv_error($validate->getError());
            }
            $postData['create_time'] = time();
            $content = $postData['content'];
            if (strlen($content) > 50){
                $content = mb_substr($content,0,50);
            }
            $checkUserIds = [];
            if (!empty($postData['user_id'])){
                $userInfos = explode(',',$postData['user_id']);
                if (!empty($userInfos)){
                    foreach ($userInfos as $index => $userInfo) {
                        $userInfo = explode('-',$userInfo);
                        if (is_numeric($userInfo[0])){
                            $checkUserIds[] = $userInfo[0];
                        }
                    }
                }
            }
//            logs('222222222', $checkUserIds);
            $addInfo = 0;
            if (!empty($checkUserIds)){
                $data = [];
                foreach ($checkUserIds as $index => $checkUserId) {
                    $data[] = [
                        'user_id'=>$checkUserId,
                        'title' => $postData['title'],
                        'content'=>$postData['content'],
                        'type'=>$postData['type'],
                        'isread'=>0,
                        'create_time'=>$postData['create_time'],
                    ];
                    $ret = umeng_send($checkUserId,$postData['title'],$content);
                    logs('faret',$ret);
                }
                // 添加多条消息
                $addInfo = Db::name('notify')->strict(false)->insertAll($data);
            }

            // -----------------------发送短信到司机手机-------------------------
            $messageArr = ['system_ordinary_info','dispatch_traveler_group'];
            // 查询所有司机的mobile
            $driverMobile = Db::name('admin_user')->where('id','in',$checkUserIds)->field('id,mobile')->select();
//            logs('driverMobile',$driverMobile);
            if ($driverMobile && in_array($postData['type'],$messageArr)){
                $mobile = '';
                foreach ($driverMobile as $index => $item) {
                    $mobile .= $item['mobile'].',';
                }
                $mobile = rtrim($mobile,',');
                // 对手机号码进行处理，每次批量发送20个手机号码
                $sendMobile = explode(',',$mobile); // 要发送的手机号码
                $ret = '';
                if (strlen($postData['content']) >= 200){
                    $postData['content'] = truncate_utf8_string($postData['content'],150).'......';
                }
                logs('content', $postData['content']);
                logs('driverMobile888',$sendMobile);
                if (count($sendMobile) <= 30){ // 一次性发送
                    logs('发送的司机号码', $mobile);
                    $ret = send_message($mobile,$postData['content']);
                }else{ // 将要发送的一维数组号码改成二维数组
                    $count = count($sendMobile); // 统计长度
                    $group = floor($count/30) + 1; // 分组
                    $sendGroupMobile = array_chunk($sendMobile,30); //电话号码二维数组
                    logs('driverMobile',$count);
                    logs('driverMobile',$group);
                    logs('driverMobile',$sendGroupMobile);
                    $sendMobiles = [];
                    foreach ($sendGroupMobile as $index03 => $item03) {
                        $sendMobiles[] = rtrim(implode(',',$item03),',');
                    }
                    if (!empty($sendMobiles)){
                        foreach ($sendMobiles as $index1 => $sendMobile1) {
                            $ret = send_message($sendMobile1,$postData['content']);
                            if (!$ret['status']){
                                break;
                            }
                        }
                    }
                }
                logs('sendMessageRet',$ret);
                if (!$ret['status']){
                    return ajax_return_adv_error('发送短信失败');
                }
            }
            if ($addInfo){
                return ajax_return_adv('添加成功');
            }else{
                return ajax_return_adv_error('添加失败');
            }
        }else{
            //定义短信类型
            $type = [
                ['name'=>'司导审核结果','value'=>'driver_check_result'],
                ['name'=>'系统普通消息','value'=>'system_ordinary_info'],
                ['name'=>'新的订单','value'=>'news_order'],
                ['name'=>'已结算','value'=>'checkouted'],
                ['name'=>'考试通过','value'=>'exam_pass'],
                ['name'=>'升级','value'=>'upgrade'],
                ['name'=>'司机升级申请','value'=>'driver_rank_apply'],
                ['name'=>'司机降级申请','value'=>'driver_degrade_appeal'],
                ['name'=>'旅客分组信息','value'=>'dispatch_traveler_group'],
            ];
            //查询用户
            $domain = $request->domain();
            $serverName = $_SERVER['SERVER_NAME'];
            $len = mb_stripos($domain,':');
            $httpDomain = substr($domain,0,$len+3).$serverName;
            $url = $httpDomain.'/admin/notify/driverInfo';
            $userInfos = Db::name('admin_user')->where('status',1)->field('id,realname')->select();
            return view('add',compact('userInfos','type','url'));
        }
    }

    public function edit(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            $rule = [
                'id'=>'require',
                'user_id'=>'require',
                'type'=>'require',
                'content'=>'require',
                'title'=>'require',
            ];
            $msg = [
                'id.require'=>'缺少参数',
                'user_id.require'=>'缺少用户',
                'type.require'=>'缺少消息类型',
                'content.require'=>'缺少内容',
                'title.require'=>'缺少标题',
            ];
            $validate = new Validate($rule,$msg);
            $result = $validate->check($postData);
            if (!$result){
                return ajax_return_adv_error($validate->getError());
            }
            $postData['update_time'] = time();//更新时间
            $up = Db::name('notify')->strict(false)->update($postData);
            if ($up){
                return ajax_return_adv('更新成功');
            }else{
                return ajax_return_adv_error('更新失败');
            }
        }else{
            $data = input();
            //查询该消息的数据
            $info  = Db::name('notify')->where('id',$data['id'])->find();
            //定义短信类型
            $type = [
                ['name'=>'司导审核结果','value'=>'driver_check_result'],
                ['name'=>'系统普通消息','value'=>'system_ordinary_info'],
                ['name'=>'新的订单','value'=>'news_order'],
                ['name'=>'已结算','value'=>'checkouted'],
                ['name'=>'考试通过','value'=>'exam_pass'],
                ['name'=>'升级','value'=>'upgrade'],
                ['name'=>'司机升级申请','value'=>'driver_rank_apply'],
                ['name'=>'司机降级申请','value'=>'driver_degrade_appeal'],
                ['name'=>'旅客分组信息','value'=>'dispatch_traveler_group'],
            ];
            //查询用户
            $userInfos = Db::name('admin_user')->where('status',1)->field('id,realname')->select();
            return view('edit',compact('userInfos','type','info'));
        }
    }

    //回收站
    public function recycleBin()
    {
        $data = input();
        if ($data['isread'] == 1){
            $map['n.isread'] = ['eq',1];
        }elseif($data['isread'] == 2){
            $map['n.isread'] = ['eq',0];
        }
        if ($data['user_name']){
            $userId = Db::name('admin_user')->where('realname','like','%'.$data['user_name'].'%')->field('id')->select();
            if ($userId){
                $userIds = '';
                foreach ($userId as $uk=>$uv){
                    $userIds .= $uv['id'].',';
                }
                $map['u.id'] = ['in',rtrim($userIds,',')];
            }
        }
        if ($data['title']){
            $map['n.title'] = ['like','%'.$data['title'].'%'];
        }
        if ($data['create_time']){
            $start_create_time = strtotime($data['create_time'].' 0:0:0');
            $end_create_time = strtotime($data['create_time'].' 23:59:59');
            $map['n.create_time'] = ['between',[$start_create_time,$end_create_time]];
        }
        if ($data['read_time']){
            $start_read_time = strtotime($data['read_time'].' 0:0:0');
            $end_read_time = strtotime($data['read_time'].' 23:59:59');
            $map['n.read_time'] = ['between',[$start_read_time,$end_read_time]];
        }
        if ($data['type'] && $data['type'] != 3){
            $map['n.type'] = $data['type'];
        }
        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
        $map['n.isdelete'] = ['eq',1];
        $list = Db::name('Notify')
            ->alias('n')
            ->join("tp_admin_user u" ,"u.id=n.user_id","left")
            ->field("n.*,u.realname")
            ->where($map)
            ->order('n.id','desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $type = [
            ['name'=>'司导审核结果','value'=>'driver_check_result'],
            ['name'=>'系统普通消息','value'=>'system_ordinary_info'],
            ['name'=>'新的订单','value'=>'news_order'],
            ['name'=>'已结算','value'=>'checkouted'],
            ['name'=>'考试通过','value'=>'exam_pass'],
            ['name'=>'升级','value'=>'upgrade'],
            ['name'=>'司机升级申请','value'=>'driver_rank_apply'],
            ['name'=>'司机降级申请','value'=>'driver_degrade_appeal'],
            ['name'=>'旅客分组信息','value'=>'dispatch_traveler_group'],
        ];

        // 模板赋值显示
        $this->view->assign('list', $list);
        $this->view->assign('type', $type);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 获取司机数据
     */
//    public function drivers(Request $request)
//    {
//        $data = input();
//        // 查询用户信息
//        $domain = $request->domain();
//        $serverName = $_SERVER['SERVER_NAME'];
//        $len = mb_stripos($domain,':');
//        $httpDomain = substr($domain,0,$len+3).$serverName;
//        $url = $httpDomain.'/admin/notify/driverInfo';
//        $list = Db::name('admin_user')->field('id,realname')->select();
//        return view('',compact('list','url'));
//    }

    public function driverInfo()
    {
        $data = input();
        if ($data['keyword']){
            // 等于1时搜索全部
            if ($data['keyword'] != 1) {
                $map['realname'] = ['like',"%{$data['keyword']}%"];
            }
        }
        $list = Db::name('admin_user')->where($map)->field('id,realname,account')->select();
//        $data = [];
        foreach ($list as $key=>$value){
            $data[] = [
                'name'=>"{$value['realname']}-{$value['account']}",
                'value'=>$value['id'],
                'selected'=>'',
                'disabled'=>''
            ];
        }
        unset($data['/admin/notify/driverInfo']);
        unset($data['keyword']);
        if (empty($data)){
            return ajax_return_error('没有数据',5,[]);
        }else{
            return ajax_return_adv('获取数据成功','','','','',(array)$data,0);
        }
    }

    public function addDriver()
    {
        // 查询条件
        $data = input();
        $map = [];
        if ($data['realname']) {
            $adminUser = Db::name('admin_user')->where('realname', 'like', "%{$data['realname']}%")->select();
            if ($adminUser) {
                $userIds = '';
                foreach ($adminUser as $index33 => $item33) {
                    $userIds .= $item33['id'] . ',';
                }
                $driverUserIds = rtrim($userIds, ',');
            }
        }
        if ($data['mobile']) {
            $adminUser = Db::name('admin_user')->where('account', 'like', "%{$data['mobile']}%")->select();
            if ($adminUser) {
                $userIds = '';
                foreach ($adminUser as $index44 => $item44) {
                    $userIds .= $item44['id'] . ',';
                }
                if (empty($driverUserIds)) {
                    $driverUserIds = rtrim($userIds, ',');
                } else {
                    $userIds = explode(',', rtrim($userIds, ','));
                    $driverUserIds = explode(',', $driverUserIds);
                    foreach ($driverUserIds as $keys => $val) {
                        if (!in_array($val, $userIds)) {
                            unset($driverUserIds[$keys]); // 删除不在这里的司机
                        }
                    }
                    $driverUserIds = empty($driverUserIds) ? '' : implode(',', $driverUserIds); // 转换成字符串
                }
            }
        }
        if ($data['seats']) {
            $map['seats'] = $data['seats'];
        }
        if ($data['car_type']) {
            $map['car_type'] = array('like', "%{$data['car_type']}%");
        }
        if ($data['car_model']) {
            $map['car_model'] = array('like', "%{$data['car_model']}%");
        }
        if ($data['vehicle_level']) {
            $map['vehicle_level'] = array('like', "%{$data['vehicle_level']}%");
        }
        if ($data['car_brand']) {
            $map['car_brand'] = array('like', "%{$data['car_brand']}%");
        }
        if ($data['driver_rank_id']) {
            if ($data['driver_rank_id'] == 5) {
                $map['driver_rank_id'] = 0;
            } else {
                $map['driver_rank_id'] = $data['driver_rank_id'];
            }
        }
        if ($data['nationality']) {
            $map['nationality'] = ['like', "%{$data['nationality']}%"];
        }
        if ($data['tag']) {
            $map['tag'] = array('like', "%{$data['tag']}%");
        }
        if (!empty($driverUserIds)){
            $map['user_id'] = ['in', $driverUserIds];
        }
        $map['isdelete'] = 0; // 查询未有删除的司机
        $driverData = Db::name('driver')->where($map)->order('id','desc')->select();
        // 查找所有司机标签
        $map_tags['isdelete'] = 0;
        $map_tags['status'] = 1;
        $driver_tags = Db::name('driver_tag')
            ->where($map_tags)
            ->select();
        $count = count($driverData);
        // 查询所有司机的等级
        $ranks = Db::name('driver_rank')->select();
        // 检测用户是否被选择
        $checkUserIds = [];
        if (!empty($data['user_info']) && is_string($data['user_info'])){
            $userInfos = explode(',',$data['user_info']);
            if (!empty($userInfos)){
                foreach ($userInfos as $index => $userInfo) {
                    $userInfo = explode('-',$userInfo);
                    if (is_numeric($userInfo[0])){
                        $checkUserIds[] = $userInfo[0];
                    }
                }
            }
        }
        $this->view->assign('ranks', $ranks);
        $this->view->assign('list', $driverData);
        $this->view->assign('driver_tags', $driver_tags);
        $this->view->assign('check_user_ids', $checkUserIds);
        $this->view->assign('count', $count);
        return $this->view->fetch('add_driver');
    }

    /**
     *  获取用户信息
     */
    public function getDriverInfos()
    {
        $data = input();
//        dump($data);
        $map = [];
        if (!empty($data['user_id'])){
            $map['id'] = ['in', $data['user_id']];
        }
        $list = Db::name('admin_user')->where($map)->field('id,realname,account')->select();
        $user = [];
        if (!empty($list)){
            foreach ($list as $index => $item) {
                $nameStr = '';
                if (!empty($item['realname'])){
                    $nameStr = "{$item['id']}-{$item['realname']}";
                }else{
                    $nameStr = "{$item['id']}-{$item['account']}";
                }
                $user[] = $nameStr;
            }
        }
        return ajax_return_adv('获取数据成功','','','','',$user);
    }
}
